import 'dart:convert';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_view/photo_view.dart';
import 'package:sph_driver/AppConfig/Config.dart';
import 'dart:io';
import 'package:image/image.dart' as img;

import '../http/NoLoadingGetApi.dart';
import '../http/NoLoadingPostApi.dart';
import '../http/api.dart';
class SubmitGoodsComplaint extends StatefulWidget {
  const SubmitGoodsComplaint({super.key, required this.dataMap, required this.parentId});
  final Map dataMap;
  final String parentId;
  @override
  State<SubmitGoodsComplaint> createState() => _SubmitGoodsComplaintState();
}

class _SubmitGoodsComplaintState extends State<SubmitGoodsComplaint> {
  String writeText="";
  List imagePaths = [];
  List base64List=[];
  String? checkImage;
  int chkecType=-1;
  List getFileList=[];
  final ImagePicker picker = new ImagePicker();
  //获取图片路径
  Future<void> uploadSingleFile(String fileData) async {
    NoLoadingApiManager.postData(
      context,
      'api/system/dev/file/uploadSingleFile',
      {
        "type":"CompanyDocument",
        "typeKey":widget.dataMap['id'],
        "fileData":fileData,
        "fileFormat":"jpg"
      },
          (responseData)  {
            getFileList.add(responseData['msg']);

      },
    );
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(widget.dataMap);
  }
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor:Color.fromRGBO(248, 248, 248, 1),
      appBar: AppBar(
        title: Text("提交投诉信息",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        centerTitle: true,
        backgroundColor: Colors.white,
      ),
    body: Column(
      children: [
        Expanded(child: ListView(
          children: [
            Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
              padding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 10.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("投诉货源",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                  SizedBox(height: 8.h,),
                  Row(
                    children: [
                      Image.network(MyServiceUrl.imgHeader+ widget.dataMap['avatarPath'],
                        width: 40.w,
                        height: 40.h,
                        fit: BoxFit.cover,
                      ),
                      SizedBox(width: 8.w,),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Container(
                                width: screenSize.width-90.w,
                                child:Text("${widget.dataMap['loadPlaceInfo'][0]['city']} ${widget.dataMap['loadPlaceInfo'][0]['county']}->${widget.dataMap['unloadPlaceInfo'][0]['city']} ${widget.dataMap['unloadPlaceInfo'][0]['county']}",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                              ),


                                ],
                          ),
                          Text("${widget.dataMap['realName']}丨${widget.dataMap['cargoInfo'][0]['cargoName']}丨${widget.dataMap['cargoInfo'][0]['packageType']}",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
              padding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 10.w,right: 10.w),
              child: Column(
                children: [
                  Row(
                    children: [
                      Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                      Text("补充描述",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                    ],
                  ),
                  SizedBox(height: 8.h,),
                  Container(
                    height: 120.h,

                    child: BrnInputText(
                      maxHeight: 100,
                      minHeight: 100,
                      minLines: 1,
                      maxLength: 200,
                      autoFocus: false,
                      bgColor: MyColors.backgreyColor,
                      textString:writeText ?? '',
                      textInputAction: TextInputAction.newline,
                      // maxHintLines: 20,
                      hint: '补充描述，便于平台更好地处理您的问题',
                      padding: EdgeInsets.fromLTRB(20, 10, 20, 14),
                      onTextChange: (text) {
                        print(text);
                        writeText = text;
                        setState(() {});
                      },
                      onSubmit: (text) {
                        print(text);
                      },
                    ),
                  )
                ],
              ),
            ),
            Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
              padding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 10.w,right: 10.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("上传凭证",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                  SizedBox(height: 8.h,),
                  Text("上传凭证，可加快客服处理",
                  style: TextStyle(color: MyColors.hintColor),),
                  Container(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Wrap(
                        spacing: 8.0,
                        runSpacing: 8.0,
                        children: [
                          ...imagePaths.map((path) => buildImageWidget(path,1)).toList(),
                          buildAddImageWidget(1),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
        ),
        Container(
          width: screenSize.width,
          height: 85.h,
          padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 15.h,bottom: 40.h),
          child: BrnSmallMainButton(
            title: '提交',
            radius: 30,
            textColor: Colors.white,
            fontSize: 16.sp,
            fontWeight: FontWeight.w600,
            bgColor: MyColors.themeColor,
            onTap: () {
              print(base64List);
              if(writeText==""){
                BrnToast.show("请填写描述信息", context);
              }else{
                // for (int i = 0; i < base64List.length; i++) {
                //   String index = base64List[i];
                //   uploadSingleFile(index);
                // }
                BrnDialogManager.showConfirmDialog(context,
                    title: "提示",
                    message:"确认提交投诉吗？",
                    cancel: "",
                    cancelWidget: GestureDetector(
                      child: Center(
                        child:  Text("我再想想",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      ),
                      onTap: (){
                        Navigator.pop(context);
                      },
                    ),
                    conformWidget:GestureDetector(
                      child: Center(
                        child:  Text("确认",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                      ),
                      onTap: (){
                        Navigator.pop(context);
                        ApiManager.postData(
                          context,
                          'api/goods/goods/contact/driverAdd',
                          {
                            "goodsId": widget.dataMap['id'],
                            "reasonTypeId": widget.parentId,
                            "description":writeText,
                            "evidenceImage":getFileList,
                            "shipperId":widget.dataMap['shipperId']
                          },
                              (responseData)  {
                            BrnToast.show("提交成功", context);
                            Navigator.pop(context);
                          },
                        );
                      },
                    ),
                    confirm:"", onConfirm: () {}, onCancel: () {
                    });
              }

            },
          ),
        ),
      ],
    ),
    );
  }

Widget buildImageWidget(String imagePath,int type) {
  return Container(
    width: 85.w,
    height: 85.h,
    child: Stack(
      children: [
        GestureDetector(
          onTap: () {
            // 处理点击查看图片的逻辑
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => ImageViewer(imagePath),
              ),
            );
          },
          child:
          imagePath.contains('https')==false?
          Container(
            width: 75.w,
            height: 75.h,
            decoration: BoxDecoration(
              image: DecorationImage(

                image: FileImage(File(imagePath)),
                fit: BoxFit.cover,
              ),
              borderRadius: BorderRadius.circular(8.0),
            ),
          ):Container(
            width: 75.w,
            height: 75.h,
            decoration: BoxDecoration(
              image: DecorationImage(

                image: NetworkImage(imagePath) ,
                fit: BoxFit.cover,
              ),
              borderRadius: BorderRadius.circular(8.0),
            ),

          ),
        ),

        Positioned(
          top: 0,
          right: 0,
          child: GestureDetector(
            child: Icon(Icons.highlight_off,size: 30,color: MyColors.authTipColor,),
            onTap: () {
              setState(() {

                print(imagePath);
                if(type==1) {
                  imagePaths.remove(imagePath);
                  if(getFileList.toSet().contains(imagePath.replaceFirst(MyServiceUrl.imgHeader, '')))
                    getFileList.remove(imagePath.replaceFirst(MyServiceUrl.imgHeader, ''));
                }

              });
            },
          ),
        ),
      ],
      alignment: Alignment.center,
    ),
  );
}

Widget buildAddImageWidget(int checkType) {
  return GestureDetector(
      onTap: () async {
        setState(() {
          chkecType=checkType;
        });
        showModalBottomSheet(context: context, builder: (BuildContext context) {
          return Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child:
            Stack(

              children: [

                Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment:MainAxisAlignment.center,

                  children:[

                    SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment:MainAxisAlignment.spaceBetween,
                      children: [
                        SizedBox(width: 30.w,),
                        Text("上传照片",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                        IconButton(onPressed: (){
                          Navigator.of(context).pop();
                        }, icon:Icon(Icons.close,color: MyColors.textColor,)),
                      ],
                    ),


                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 38.w,),
                        GestureDetector(
                          child:   Column(
                            children: [
                              Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                              Text("相册",style: TextStyle(color: Colors.black),),

                            ],

                          ),
                          onTap: ()async{
                            Navigator.of(context).pop();
                            final pickedFile = await picker.pickImage(source: ImageSource.gallery);

                            if (pickedFile != null) {

                              setState(() {
                                checkImage = pickedFile.path;
                                printImageMemorySize(File(checkImage!));
                                print(checkImage);
                                compressImage(File(checkImage!));
                              });
                            }
                          },
                        ),

                        SizedBox(width: 38.w,),
                        GestureDetector(
                          child: Column(
                            children: [
                              Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                              Text("拍照",style: TextStyle(color: Colors.black),),

                            ],

                          ),
                          onTap: ()async{
                            Navigator.of(context).pop();
                            final pickedFile = await picker.pickImage(source: ImageSource.camera);

                            if (pickedFile != null) {
                              setState(() {
                                checkImage = pickedFile.path;
                                printImageMemorySize(File(checkImage!));
                                print(checkImage);
                                compressImage(File(checkImage!));

                              });
                            }
                          },
                        ),

                      ],
                    ),
                    SizedBox(height: 40.h,),
                  ],

                ),

              ],

            ),
          );


        });


      },
      child: Image.asset("lib/Images/OrderList/图片管理上传照片.png",width: 85.w,height: 85.h,)
  );
}

void printImageMemorySize(File imageFile) {
  List<int> imageBytes = imageFile.readAsBytesSync();
  print('Original Image Memory Size: ${imageBytes.length} bytes');
}

Future<void> compressImage(File imageFile) async {
  List<int> imageBytes = await imageFile.readAsBytes();
  img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

  // Adjust the quality and size as needed
  img.Image compressedImage = img.copyResize(image, width: 1024);

  List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

  // Create a new File for the compressed image
  File compressedFile = File('${imageFile.path}_compressed.jpg');
  await compressedFile.writeAsBytes(compressedBytes);

  print('Compressed Image Size: ${compressedBytes.length} bytes');

  convertToBase64(compressedFile);
}

Future<void> convertToBase64(File imageFile) async {
  List<int> imageBytes = await imageFile.readAsBytes();
  String base64String = base64Encode(imageBytes);

  setState(() {

    if(chkecType==1){
      imagePaths.add(checkImage.toString());
      base64List.add(base64String);
      for (int i = 0; i < base64List.length; i++) {
        String index = base64List[i];
        uploadSingleFile(index);
      }
    }


  });
}


}
class ImageViewer extends StatelessWidget {
  final String imagePath;

  ImageViewer(this.imagePath);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          // 当点击大图时，返回上一个页面
          Navigator.pop(context);
        },
        child: PhotoView(
          imageProvider: FileImage(File(imagePath)),
          minScale: PhotoViewComputedScale.contained * 0.8,
          maxScale: PhotoViewComputedScale.covered * 2,
        ),
      ),
    );
  }
}